package com.elite.groovy.callback

import com.elite.groovy.kh.KHUtil
import com.elite.groovy.util.EliteBean
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.text.DateFormat
import java.text.SimpleDateFormat
import java.time.Duration
import java.time.LocalDateTime

/**
* @Title:
* @Description:节假日API提供，天润通过调用该api识别德高客服工作时间
* @Param:
* @return:
* @Author:TH
* @Date: 2023/10/26
*/
public class apiIVRGetHoliday implements ServiceBackInvoke {

    private static final Log log = LogFactory.getLog(apiIVRGetHoliday.class);

    @Override
    String doCallBack(EliteBean eliteBean, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

        // 初始化返回参数
        JSONObject result = new JSONObject();

        // 获取接口调用方式及参数
        String getMethod = httpServletRequest.getMethod();
        log.debug("[getMethod]:" + getMethod);

        String inData = "";
        if (getMethod.equals("GET")) {
            inData = httpServletRequest.getParameter("data");
            log.debug("[原始Get请求参数]:" + inData);
        } else {
            InputStreamReader reader = new InputStreamReader(httpServletRequest.getInputStream(), "UTF-8");
            BufferedReader iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                inData += line;
            }
            log.debug("[原始Post请求参数]:" + inData);
        }
        log.info("[调用请求信息]:" + inData);

        //  入参为空
        if (KHUtil.isNull(inData)) {
            log.debug("【德高客服工作时间查询API接口】入参为空-无法完成操作!");
            result.put("status", -2);
            result.put("msg", "入参为空-无法完成操作!");
            result.put("data", "{}");
            //写入接口日志表
            String logsql = "insert into dg_api_log(rec_guid,api_type,request_body,back_body,request_time,remarks)values(uuid(),?,?,?,now(),?)";
            jt.update(logsql, "apiGetHoliday", inData.toString(), result.toString(), "德高客服工作时间查询API接口");
            return result.toString();
        }


        try {

            //解析请求的jSON
            JSONObject inJson = JSONObject.fromObject(inData);
            String pretplcode = inJson.getString("pretplcode");
            String tag = inJson.getString("tag");
            String segment = inJson.getString("segment");
            String posttplcode = inJson.getString("posttplcode");
            String datefmt = inJson.getString("datefmt");//日期 格式YYYY-MM-DD

            //判断入参日期格式是否正确
            DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            try {
                Date date = formatter.parse(datefmt);
                log.debug("【德高客服工作时间查询API接口】datefmt输入的日期格式正确：" + date);
            } catch (Exception e) {
                result.put("status", -1);
                result.put("msg", "datefmt输入的日期格式错误[" + e.getMessage() + "]");
                result.put("data", "{}");
                //写入接口日志表
                String logsql = "insert into dg_api_log(rec_guid,api_type,request_body,back_body,request_time,remarks)values(uuid(),?,?,?,now(),?)";
                jt.update(logsql, "apiGetHoliday", inData.toString(), result.toString(), "德高客服工作时间查询API接口");
                log.error("【德高客服工作时间查询API接口】datefmt输入的日期格式错误：" + datefmt);

                return result.toString();
            }
            //校验参数是否为空
            if (KHUtil.isNull(pretplcode) || KHUtil.isNull(segment) || KHUtil.isNull(posttplcode) || KHUtil.isNull(datefmt)) {
                log.debug("【德高客服工作时间查询API接口】参数值为空-无法完成操作!");
                result.put("status", -2);
                result.put("msg", "参数值为空-无法完成操作!");
                result.put("data", "{}");
                //写入接口日志表
                String logsql = "insert into dg_api_log(rec_guid,api_type,request_body,back_body,request_time,remarks)values(uuid(),?,?,?,now(),?)";
                jt.update(logsql, "apiGetHoliday", inData.toString(), result.toString(), "德高客服工作时间查询API接口");
                return result.toString();
            }

            //判断是否是约定好的固定值
            if (!pretplcode.equals("Local_Interface_input") || !segment.equals("formcond") || !posttplcode.equals("Interface_out_detail")|| !tag.equals("tianrun") ) {
                log.debug("【德高客服工作时间查询API接口】固定值不正确-无法完成操作!");
                result.put("status", -2);
                result.put("msg", "固定值不正确-无法完成操作!");
                result.put("data", "{}");
                //写入接口日志表
                String logsql = "insert into dg_api_log(rec_guid,api_type,request_body,back_body,request_time,remarks)values(uuid(),?,?,?,now(),?)";
                jt.update(logsql, "apiGetHoliday", inData.toString(), result.toString(), "德高客服工作时间查询API接口");
                return result.toString();
            }


            //校验通过-->开始查找对应参数日期下的德高客服工作时间
            String selectsql = ''' Select c.work_starttime,c.work_endtime,c.noon_starttime,c.noon_endtime,c.DATETYPE,s.datetypedesc
                         from c_freedate c
                          left join SYSC_DATETYPE s on c.DATETYPE=s.datetypeid
                          where  FREEDATE=DATE_FORMAT(?,'%Y-%m-%d 00:00:00') 
                          and (c.work_starttime is not null  and c.work_starttime !='') 
                          and (c.work_endtime is not null and c.work_endtime !='' )
                          and (c.noon_starttime is not null and c.noon_starttime !='')
                          and (c.noon_endtime is not null and c.noon_endtime!='' )
                          limit 1   ''';
            List<Map<String, Object>> selelctList = jt.queryForList(selectsql, datefmt);

            if (selelctList.size() > 0) {

                String work_starttime = selelctList.get(0).get("work_starttime");//工作开始时间
                String work_endtime = selelctList.get(0).get("work_endtime");//工作结束时间
                String noon_starttime = selelctList.get(0).get("noon_starttime");//午休开始时间
                String noon_endtime = selelctList.get(0).get("noon_endtime");//午休结束时间
                String DATETYPE = selelctList.get(0).get("DATETYPE");//日期类型
                String datetypedesc = selelctList.get(0).get("datetypedesc");//节日类型

                String workday;
                log.debug("日期类型：" + DATETYPE)
                //判断是否是000010 ,如果是的话则是工作日否则是非工作日
                if (DATETYPE.equals("000010")) {
                     workday = "工作日";
                } else {
                     workday = "非工作日";
                }
                 String strend=datefmt+'T'+noon_endtime;
                String strsta=datefmt+'T'+noon_starttime;


                LocalDateTime start = LocalDateTime.parse(strsta);
                LocalDateTime end = LocalDateTime.parse(strend);
                Duration duration = Duration.between(start, end);
                long minutes = duration.toMinutes();
                String breaktime=minutes;


                result.put("InterfaceCode","sys_get_workday");
                result.put("posttplcode","Interface_out_detail");
                result.put("pretplcode","Local_Interface_input");
                result.put("segment","formcond");
                result.put("tag","tianrun");
                result.put("uid","/extapi");
                result.put("company","davco");
                result.put("breaktime",breaktime);
                result.put("workday",workday);
                result.put("holiday",datetypedesc);
                result.put("workstart",work_starttime);
                result.put("workend",work_endtime);
                result.put("breakstarttime",noon_starttime);
                result.put("breakendtime",noon_endtime);







                log.debug("【德高客服工作时间查询API接口】成功返回的JSON报文："+result);
                //写入接口日志表
                String logsql="insert into dg_api_log(rec_guid,api_type,request_body,back_body,request_time,remarks)values(uuid(),?,?,?,now(),?)";
                jt.update(logsql, "apiGetHoliday",inData.toString(),result.toString(),"德高客服工作时间查询API接口");


            } else {
                log.debug("【德高客服工作时间查询API接口】该日期还没有维护工作时间!");
                result.put("status", -2);
                result.put("msg", "该日期还没有维护工作时间-无法完成操作!");
                result.put("data", "{}");
                //写入接口日志表
                String logsql = "insert into dg_api_log(rec_guid,api_type,request_body,back_body,request_time,remarks)values(uuid(),?,?,?,now(),?)";
                jt.update(logsql, "apiGetHoliday", inData.toString(), result.toString(), "德高客服工作时间查询API接口");
                return result.toString();

            }


        } catch (Exception e) {
            log.error("【德高客服工作时间查询API接口】数据处理错误:", e);
            result.put("status", -1);
            result.put("msg", "数据处理错误[" + e.getMessage() + "]");
            result.put("data", "{}");

            //写入接口日志表
            String logsql = "insert into dg_api_log(rec_guid,api_type,request_body,back_body,request_time,remarks)values(uuid(),?,?,?,now(),?)";
            jt.update(logsql, "apiGetHoliday", inData.toString(), result.toString(), "德高客服工作时间查询API接口");
        }


        return result
    }
}
